"""
主页面视图控制器
处理主页和相关路由
"""
from flask import Blueprint, render_template, redirect, url_for, flash
from flask_login import current_user, login_required
from app.models.user import User
from app.models.role import Role, Permission
from app import db
from datetime import datetime, timedelta

main_bp = Blueprint('main', __name__)


@main_bp.route('/')
def index():
    """主页"""
    # 获取一些统计数据用于展示
    stats = {
        'total_users': User.query.count(),
        'total_roles': Role.query.count(),
        'total_permissions': Permission.query.count(),
        'recent_users': User.query.filter(
            User.created_at >= datetime.utcnow() - timedelta(days=30)
        ).count()
    }
    
    return render_template('main/index.html', stats=stats)


@main_bp.route('/about')
def about():
    """关于页面"""
    return render_template('main/about.html')


@main_bp.route('/dashboard')
@login_required
def dashboard():
    """用户仪表板"""
    # 获取用户相关的统计数据
    user_stats = {
        'login_count': current_user.login_count,
        'last_login': current_user.last_login,
        'created_at': current_user.created_at,
        'roles': current_user.roles,
        'permissions': current_user.get_permissions()
    }
    
    return render_template('main/dashboard.html', user_stats=user_stats)